from reportlab.lib.styles import ParagraphStyle as PS
from reportlab.platypus import PageBreak
from reportlab.platypus.tableofcontents import Table
from reportlab.platypus.paragraph import Paragraph
from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate
from reportlab.platypus.tableofcontents import TableOfContents
from reportlab.platypus.frames import Frame
from reportlab.lib.units import cm
import sys
import time
import os

sys.path[0]
cont = sys.path[0].find('pygb-gerenciador-de-biblioteca') + 30
sys.path[0] = sys.path[0]+"/banco"
from bd import *
sys.path[0] = sys.path[0][:cont]




class MyDocTemplate(BaseDocTemplate):
    def __init__(self, filename, **kw):
        self.allowSplitting = 0
        BaseDocTemplate.__init__(self, filename, **kw)
        template = PageTemplate('normal', [Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')])
        self.addPageTemplates(template)
    def afterFlowable(self, flowable):
        "Registers TOC entries."
        if flowable.__class__.__name__ == 'Paragraph':
            text = flowable.getPlainText()
            style = flowable.style.name
            if style == 'Heading1':
                self.notify('TOCEntry', (0, text, self.page))
            if style == 'Heading2':
                self.notify('TOCEntry', (1, text, self.page))


class relatoriocliente:
    def __init__ (self):
        h1 = PS(name = 'Heading1',
               fontSize = 9,
               leading = 16
               )
        h2 = PS(name = 'Heading2',
               fontSize = 12,
               leading = 16,
               leftIndent = 10)
        # Build story.
        story = []
        toc = TableOfContents()

        # For conciseness we use the same styles for headings and TOC entries

        result =  bancocliente().GetClientes()

        x = 0
        for i in result:
            clientee = 'Codigo : %s |  Nome: %s | Telefone: %s' %(i[0],i[1],i[7])
            story.append(Paragraph(clientee, h1))
            x += 1
            if x == 43:
                story.append(PageBreak())


        key = time.localtime()
        key = '%d%d%d%d%d%d' %(key[2],key[1],key[0],key[3],key[4],key[5])
        name ='relatoriocliente/cliente%s.pdf' %(key)
        doc = MyDocTemplate(name)
        doc.multiBuild(story)
        os.system("start "+ name);

